package cn.doways.api.controller;

import cn.doways.api.auth.JwtAuthenticationRequest;
import cn.doways.api.auth.JwtAuthenticationResponse;
import cn.doways.api.dto.Result;
import cn.doways.api.entity.Secret;
import cn.doways.api.service.UsersService;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import javax.security.sasl.AuthenticationException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;


/**
 * @ClassName StudentController
 * @Description //TODO
 * @Author shellming
 * @Date 2019-08-08 06:36
 **/
@RestController
public class AuthController {


    @Value("${jwt.header}")
    private String tokenHeader;

    @Autowired
    private UsersService usersService;



    @GetMapping(value = "/auth/{id}")
    @ApiOperation(value = "根据学生ID（学号）获得姓名",tags = {"公共"},notes = "GET请求注意观察返回结果")
    public Result<String> getNameById( @PathVariable("id") String id){
       try{
           return Result.success(usersService.getNameById(id).getName());
       }catch (NullPointerException n){
           return Result.error("学号未定义！");
       }

    }




    @PostMapping(value = "/auth/register")
    @ApiOperation(value = "手机号注册绑定",tags = {"公共"},notes = "POST请求注意观察返回结果，有两种状态200和404，200代表操作成功，404代表失败，data里会显示错误信息")
    public Result<String> saveStudent(@RequestBody Secret secret, HttpSession session){
        try {
            session.getAttribute(secret.getPhoneNumber());
            if(!session.getAttribute(secret.getPhoneNumber()).toString().equals(secret.getSmsCode())){
                return Result.error("无效的验证码",null);
            }else {
                session.removeAttribute(secret.getPhoneNumber());
                if(usersService.studentRegister(secret)==0){
                    return Result.error("用户已存在",0+"");
                }else {
                    return Result.success(1+"");
                }
            }
        }catch (Exception e){
            return Result.error("无Session记录", e.toString());
        }

    }



    @PostMapping(value = "/auth")
    @ApiOperation(value = "授权鉴权",tags = {"公共"},notes = "发送一个包含username和password的Json数据的Post请求")
    public Result<String> auth(@RequestBody JwtAuthenticationRequest authenticationRequest)throws AuthenticationException {

            final String token= usersService.login(authenticationRequest.getUsername(),authenticationRequest.getPassword());
            if (token.length()>10){
                return Result.success(new JwtAuthenticationResponse(token).getToken());
            }else {
                return Result.error(token,null);
            }
    }



    @GetMapping(value = "/auth/refreash")
    @ApiOperation(value = "Token刷新",tags = "公共",notes = "发送一个包含旧的Token的Header，Header里包含字段Authorization值为旧的Token")
    public Result<String> refresh(HttpServletRequest request)throws AuthenticationException{
        String token = request.getHeader(tokenHeader);
        String reToken = usersService.refreash(token);
        if (reToken.length()>15){
            return Result.success(new JwtAuthenticationResponse(reToken).getToken());
        }else {
            return Result.error(reToken,null);
        }
    }



    @DeleteMapping(value = "/auth/logout")
    @ApiOperation(value = "退出登陆",tags = "公共",notes = "发送一个包含现有Token的Header，Header里包含字段Authorization值为现有的Token")
    public Result<String> logout(HttpServletRequest request)throws AuthenticationException{
        try{
            String token = request.getHeader(tokenHeader);
            int msg = usersService.logout(token);
            if (msg==1){
                return Result.error("行啊小伙伪造Token");
            }else if(msg==2){
                return Result.error("早已推出");
            }else {
                return Result.success("exit(1)");
            }
        }catch (NullPointerException e){
            return Result.error(e.toString());
        }

    }


}
